package com.ltu.config.resttemplate;

import java.io.IOException;
import java.util.Iterator;

import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import com.ltu.enums.EnumUtils;
import com.ltu.enums.SysDict;
import com.ltu.enums.SysDict.ThirdPartyDict;
import com.ltu.rest.ThirdPartyHeader;
import com.ltu.util.SpringContextHolder;
import com.ltu.util.redis.RedistUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j										
public class RestFilterAddHalder implements ClientHttpRequestInterceptor {

	@Override
	public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
			throws IOException {
		
		String url =request.getURI().toString() ;
		//针对不同平台的设置各自的header
		ThirdPartyDict dict =	getDict(url);
		if(dict!=null) {
//			request.getHeaders().clear();
			ThirdPartyHeader tph =	SpringContextHolder.getBean(dict.getValue()); 
			tph.setRestHeader(request);
		}
		request.getHeaders().add("accept", "*/*");	
//		request.getHeaders().add("Content-Type", "application/json");
		Integer length = body.length;
		request.getHeaders().add("Content-Length", length.toString());
//		String param =  request.getHeaders().getPragma();
		log.info("\n 请求地址：{}, 请求头：{},\n 请求体：{},\n 请求方式：{}",url ,request.getHeaders().toString() ,new String(body,"UTF-8"),request.getMethodValue());
		ClientHttpResponse response = execution.execute(request, body);
		log.info("\n 请求地址：{}, 第三方请求 HTTP状态：{},描述：{},响应body:{}",url,response.getStatusCode(),response.getStatusText());
		return response;
	}
	
	private ThirdPartyDict getDict(String url ) {
		ThirdPartyDict[] dicts = SysDict.ThirdPartyDict.values();
		for (int i = 0; i < dicts.length; i++) {
			if (url.indexOf(dicts[i].getName())>-1)
				return  dicts[i];
		}
		return null;
	}

}
